<?php

App::uses('AppController', 'Controller');

class KlijentiController extends AppController {
	
	public $uses = array('Client', 'Store');
	
	public function index() {
		$this->set("data", $this->Client->find("all"));
	}
	
	public function pregled($id) {
		$this->set("data", $this->Client->findById($id));
	}
	
	public function novi() {
		$this->render("form");
	}
	
	public function izmeni($id) {
		$this->set("data", $this->Client->findById($id));
		$this->render("form");
	}
	
	public function sacuvaj() {
		if(!empty($this->data)) {
			$data = $this->data;
			$this->set("data", $data);
			
			if(floatval($data['ClientRebate'][-1]['value'])==0 || empty($data['ClientRebate'][-1]['effective_date'])){
				unset($data['ClientRebate'][-1]);
			}
            if(intval($data['ClientPayingCurrency'][-1]['value'])<1 || empty($data['ClientPayingCurrency'][-1]['effective_date'])){
				unset($data['ClientPayingCurrency'][-1]);
			}
			
			$this->Client->create($data);
			$this->Client->set($data);
			
			if($this->Client->validates()){
				$this->Client->ClientRebate->deleteAll(array("client_id"=>$this->Client->id));
                $this->Client->ClientPayingCurrency->deleteAll(array("client_id"=>$this->Client->id));
                if($this->Client->saveAll($data)) {
					$this->setFlash("Klijent je uspešno sačuvan.", "ok");
					$this->redirect('izmeni/'.$this->Client->id);
				}else{
					$this->setFlash("Čuvanje nije uspelo." . var_export($this->Client->validationErrors, true));
					return $this->render("form");
				}
			}else{
				$this->setFlash("Uneti podaci nisu validni. Čuvanje nije uspelo.");
				return $this->render("form");
			}
		}
		$this->redirect("index");
	}
	
	public function obrisi($id) {
		if($this->Client->delete($id)) {
			$this->setFlash("Klijent je obrisan.");
		}
		$this->redirect("index");
	}
	
	public function rabat($id, $date) {
	    $this->autoRender = false;
	    $value = 0;
	    
	    if($store = $this->Store->findById($id)) {
	        $client_id = $store['Client']['id'];
    	    $rabat = $this->Client->ClientRebate->find('first', array(
    	        'fields' => 'value',
    	        'conditions' => array(
    	            'client_id' => $client_id,
    	            'effective_date <=' => $date
    	        ),
    	        'order' => 'effective_date DESC'
    	    ));
    	    
    	    if($rabat) {
    	        $value = Set::extract($rabat, 'ClientRebate.value');
    	    }
	    }
	    
	    echo $value;
	}
}

?>